import * as fs from "fs";
import { fileURLToPath } from "url";
import path from "path";
import type { Stats } from "fs";

/**
 * @description: 检测本地文件或文件夹是否存在
 * @param {string} url 文件路径
 * @return {*}
 * @author: zhj1214
 */
export const getStat = function (url: string) {
  return new Promise((resolve, reject) => {
    fs.stat(url || "", (err, stats) => {
      err ? reject(err) : resolve(stats);
    });
  });
};
/**
 * @description: 异步-创建文件，并写入内容
 * @param {string} writePath 路径
 * @param {string} content 内容
 * @author: zhj1214
 */
export const creatContentToPath = (writePath: string, content: string) => {
  // 开始写入内容
  fs.writeFile(writePath, content, (err) => {
    if (err) {
      console.error("Error creating file:", err);
      return false;
    } else {
      return true;
    }
  });
};
/**
 * @description: 异步-创建文件，并写入内容
 * @param {string} writePath 路径
 * @param {string} content 内容
 * @author: zhj1214
 */
export const creatContentToPathSync = (writePath: string, content: string) => {
  // 开始写入内容
  try {
    fs.writeFileSync(writePath, content);
    // console.log("JSON 文件被成功创建和保存");
    return true;
  } catch (err) {
    console.error("写入 JSON 文件时发生错误:", err);
    return err;
  }
};

/**
 * @description: 同步创建目录
 * @param {string} recursive 这意味着如果父目录不存在，它们也会被创建
 */
export const createDirectorySync = (dirPath: string) => {
  try {
    fs.mkdirSync(dirPath, { recursive: true });
    console.log("目录创建成功");
    return true;
  } catch (err) {
    console.error("创建目录时出错：", err);
    return false;
  }
};

/**
 * @description: 时间格式化
 * @param {Date} date
 * @return {*} 输出年月日时分秒
 */
export const formatDate = (date: Date) => {
  // 补零函数
  const pad = (num: number) => (num < 10 ? "0" + num : num);

  // 获取日期各个部分
  const year = date.getFullYear();
  const month = pad(date.getMonth() + 1); // 月份是从0开始的
  const day = pad(date.getDate());
  const hours = pad(date.getHours());
  const minutes = pad(date.getMinutes());
  const seconds = pad(date.getSeconds());

  // 拼接成最终字符串
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

/**
 * @description: 获取当前目录下的:目录,和文件路径
 * @param {string} pipe
 * @param {string} fileNmae
 * @return {*}
 */
export const getCurrentDirPath = (pipe: string, fileNmae?: string) => {
  // 获取当前文件的 Path
  const __filename = fileURLToPath(import.meta.url);
  // 获取当前文件所在的目录
  const __dirname = path.dirname(__filename);
  const parnentDir = path.dirname(__dirname);
  // 根目录,文件路径
  const filePathRoot = path.join(
    __dirname,
    "../../",
    "",
    fileNmae || "log.json"
  );

  // 定义路径
  const writePath = `${parnentDir}${pipe}`; // 目录
  let filePath = "";
  if (fileNmae) {
    filePath = `${writePath}/${fileNmae}`; // 文件路径
  }

  return { filePathRoot, writePath, filePath };
};

/**
 * @description: 路径是否存在
 * @param {string} path 路径
 */
export const isExistPath = async (path: string) => {
  if (!path) return false;
  try {
    return !!((await getStat(path)) as Stats);
  } catch (error) {
    return false;
  }
};
